﻿Imports System.IO
Imports System.Linq
Imports CommonMark
Imports Markdig

Imports System.Xml




Public Class frmMain

    Public previousSelectedNode As TreeNode = Nothing
    Public previousSelectedItem As ListViewItem = Nothing
    Public estilo As String


    Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click
        frmSplash.ShowDialog()
    End Sub

    Private Sub doc_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles doc.TextChanged
        'FindDialog.fp.Text = doc.Text
        cc.Text = Len(doc.Text)
        lc.Text = doc.Lines.Length
        Label1.Text = WordCount.CountWords2(doc.Text)
        Label2.Text = UpdateBookLength(TreeView1.SelectedNode)
        Label8.Text = Math.Round(CDbl(Label2.Text) / 522, 1)
    End Sub


    Public Sub iniciar(path As String)

        Try
            Dim P As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
            P = New Uri(P).LocalPath

            estilo = File.ReadAllText(P & "/styles/gitub.css")
            ListView1.Columns(0).Width = 250           
            ListView1.Columns(1).Width = 140
            TreeView1.Nodes.Clear()
            Dim mRootNode As New TreeNode
            mRootNode.Text = path
            mRootNode.Tag = path
            mRootNode.Nodes.Add("*DUMMY*")
            TreeView1.Nodes.Add(mRootNode)
            TreeView1.Nodes(0).Expand()

        Catch ex As Exception

        End Try



    End Sub


    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        My.Application.MinimumSplashScreenDisplayTime = 2000

        Dim file As New MadMilkman.Ini.IniFile
        Dim P As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
        P = New Uri(P).LocalPath
        file.Load(P & "/config.ini.txt")
        Dim sec As MadMilkman.Ini.IniSection
        sec = file.Sections(0)
        iniciar(sec.Keys(0).Value)

    End Sub


    Private Sub TreeView1_BeforeExpand(sender As System.Object, e As System.Windows.Forms.TreeViewCancelEventArgs) Handles TreeView1.BeforeExpand

        Try
            doc.Clear()
            Label1.Text = ""

            e.Node.Nodes.Clear()
            ' get the directory representing this node
            Dim mNodeDirectory As IO.DirectoryInfo
            mNodeDirectory = New IO.DirectoryInfo(e.Node.Tag.ToString)
            ' add each subdirectory from the file system to the expanding node as a child node
            For Each mDirectory As IO.DirectoryInfo In mNodeDirectory.GetDirectories
                ' declare a child TreeNode for the next subdirectory
                Dim mDirectoryNode As New TreeNode
                ' store the full path to this directory in the child TreeNode's Tag property
                mDirectoryNode.Tag = mDirectory.FullName
                ' set the child TreeNodes's display text
                mDirectoryNode.Text = mDirectory.Name
                ' add a dummy TreeNode to this child TreeNode to make it expandable
                mDirectoryNode.Nodes.Add("*DUMMY*")
                ' add this child TreeNode to the expanding TreeNode
                e.Node.Nodes.Add(mDirectoryNode)
            Next

        Catch ex As Exception

        End Try

    End Sub



    Private Sub TreeView1_AfterSelect(sender As System.Object, e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect


        Try
            Dim strContenido As String
            Dim totalLength As Integer

            If previousSelectedNode IsNot Nothing Then
                previousSelectedNode.BackColor = TreeView1.BackColor
                previousSelectedNode.ForeColor = TreeView1.ForeColor
            End If

            doc.Clear()
            Label1.Text = ""

            Dim CurrentNode As TreeNode = e.Node
            Dim fullpath As String = CurrentNode.FullPath
            Dim dirInfo As New DirectoryInfo(fullpath)
            Dim fileInfo As FileInfo
            Dim strFile As String

            ListView1.Items.Clear()
            doc.Clear()
            WebBrowser1.DocumentText = ""
            txtNoteName.Clear()

            For Each fileInfo In dirInfo.GetFiles("*.txt").OrderByDescending(Function(f) f.LastWriteTime).ToList()

                Dim li As New ListViewItem(New String() {fileInfo.Name, fileInfo.LastWriteTime})
                ListView1.Items.Add(li)
                strFile = TreeView1.SelectedNode.FullPath & "\" & fileInfo.Name
                strContenido = My.Computer.FileSystem.ReadAllText(strFile)
                totalLength = totalLength + WordCount.CountWords2(strContenido)

            Next

            Label2.Text = UpdateBookLength(e.Node)
            Label8.Text = Math.Round(CDbl(Label2.Text) / 522, 1)


        Catch ex As Exception

        End Try



    End Sub


    Public Function UpdateBookLength(nodo As TreeNode) As Integer

        Try
            Dim strContenido As String
            Dim totalLength As Integer

            Dim CurrentNode As TreeNode = nodo
            Dim fullpath As String = CurrentNode.FullPath

            Dim dirInfo As New DirectoryInfo(fullpath)
            Dim fileInfo As FileInfo
            Dim strFile As String


            For Each fileInfo In dirInfo.GetFiles("*.txt").OrderByDescending(Function(f) f.LastWriteTime).ToList()

                strFile = TreeView1.SelectedNode.FullPath & "\" & fileInfo.Name
                strContenido = My.Computer.FileSystem.ReadAllText(strFile)
                totalLength = totalLength + WordCount.CountWords2(strContenido)

            Next

            Return totalLength
        Catch ex As Exception
            Return 0
        End Try



    End Function


    Private Sub ListView1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListView1.SelectedIndexChanged

        Try

            TabControl1.SelectedTab = TabPage2

            If previousSelectedItem IsNot Nothing Then
                previousSelectedItem.BackColor = ListView1.BackColor
                previousSelectedItem.ForeColor = ListView1.ForeColor
            End If

            doc.Clear()
            txtNoteName.Clear()
            Label1.Text = ""

            Dim strFile As String
            strFile = TreeView1.SelectedNode.FullPath & "\" & ListView1.SelectedItems(0).Text
            txtNoteName.Text = ListView1.SelectedItems(0).Text

            doc.Text = CStr(My.Computer.FileSystem.ReadAllText(strFile)).Replace(vbLf, vbCrLf) 'a formato windows

            Label1.Text = WordCount.CountWords2(doc.Text)

            Dim md As String
            Dim pipeline As MarkdownPipeline = New MarkdownPipelineBuilder().UseAdvancedExtensions().Build()
            md = Markdown.ToHtml(CStr(My.Computer.FileSystem.ReadAllText(strFile)), pipeline)

            WebBrowser1.DocumentText = (estilo & md).Replace("<img src=" & Chr(34), "<img src=" & Chr(34) & TreeView1.SelectedNode.FullPath & "\")

        Catch ex As Exception

        End Try

    End Sub


    Sub guardar()
        Try


            Dim strFile As String
            'strFile = TreeView1.SelectedNode.FullPath & "\" & ListView1.SelectedItems(0).Text
            strFile = TreeView1.SelectedNode.FullPath & "\" & txtNoteName.Text

            Dim strContent_old As String
            Dim strContent_current As String

            strContent_old = CStr(My.Computer.FileSystem.ReadAllText(strFile)).Replace(vbLf, vbCrLf)
            strContent_current = doc.Text


            If strContent_old <> strContent_current Then

                'Borra
                My.Computer.FileSystem.DeleteFile(strFile)

                'Crea
                strFile = TreeView1.SelectedNode.FullPath & "\" & txtNoteName.Text
                My.Computer.FileSystem.WriteAllText(strFile, doc.Text.Replace(vbCrLf, vbLf), False) 'Guarda en formato android

            End If

            'Actualiza listview
            Dim CurrentNode As TreeNode = TreeView1.SelectedNode
            Dim fullpath As String = CurrentNode.FullPath

            Dim dirInfo As New DirectoryInfo(fullpath)
            Dim fileInfo As FileInfo

            ListView1.Items.Clear()
            For Each fileInfo In dirInfo.GetFiles("*.txt").OrderByDescending(Function(f) f.LastWriteTime).ToList()
                Dim li As New ListViewItem(New String() {fileInfo.Name, fileInfo.LastWriteTime})
                ListView1.Items.Add(li)
            Next


        Catch ex As Exception
            ''MsgBox(ex.Message)
        End Try
    End Sub


    Private Sub doc_Leave(sender As System.Object, e As System.EventArgs) Handles doc.Leave
        guardar()
    End Sub

    Private Sub txtNoteName_Leave(sender As System.Object, e As System.EventArgs) Handles txtNoteName.Leave


        Try

            Dim strFile As String
            strFile = TreeView1.SelectedNode.FullPath & "\" & ListView1.SelectedItems(0).Text

            'Borra
            My.Computer.FileSystem.DeleteFile(strFile)

            'Crea
            strFile = TreeView1.SelectedNode.FullPath & "\" & txtNoteName.Text
            My.Computer.FileSystem.WriteAllText(strFile, doc.Text.Replace(vbCrLf, vbLf), False) 'Guarda en formato Android


            'Actualiza listview
            Dim CurrentNode As TreeNode = TreeView1.SelectedNode
            Dim fullpath As String = CurrentNode.FullPath

            Dim dirInfo As New DirectoryInfo(fullpath)
            Dim fileInfo As FileInfo

            ListView1.Items.Clear()
            'For Each fileInfo In dirInfo.GetFiles("*.txt")
            For Each fileInfo In dirInfo.GetFiles("*.txt").OrderByDescending(Function(f) f.LastWriteTime).ToList()
                'Dim li As New ListViewItem(fileInfo.Name) ' or FullName if you want to include the path

                Dim li As New ListViewItem(New String() {fileInfo.Name, fileInfo.LastWriteTime})

                ListView1.Items.Add(li)
            Next


        Catch ex As Exception

        End Try


    End Sub



    Private Sub TreeView1_Validating(sender As System.Object, e As System.ComponentModel.CancelEventArgs) Handles TreeView1.Validating
        TreeView1.SelectedNode.BackColor = SystemColors.Highlight
        TreeView1.SelectedNode.ForeColor = Color.White
        previousSelectedNode = TreeView1.SelectedNode
    End Sub

    Private Sub ListView1_Validating(sender As System.Object, e As System.ComponentModel.CancelEventArgs) Handles ListView1.Validating

        Try
            ListView1.SelectedItems(0).BackColor = SystemColors.Highlight
            ListView1.SelectedItems(0).ForeColor = Color.White
            previousSelectedItem = ListView1.SelectedItems(0)

        Catch ex As Exception

        End Try

    End Sub


    Private Sub NuevaNotaToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles NuevaNotaToolStripMenuItem.Click


        Dim strFile As String

        'Crea
        strFile = TreeView1.SelectedNode.FullPath & "\" & "nueva_nota_" & Now.ToString("yyyyMMddHHmmss") & ".txt"
        My.Computer.FileSystem.WriteAllText(strFile, doc.Text.Replace(vbCrLf, vbLf), False) 'Guarda en formato Android

        'Refrescar
        UpdateListNotas()


    End Sub

    Public Sub UpdateListNotas()

        Try

            'Actualiza listview
            Dim CurrentNode As TreeNode = TreeView1.SelectedNode
            Dim fullpath As String = CurrentNode.FullPath

            Dim dirInfo As New DirectoryInfo(fullpath)
            Dim fileInfo As FileInfo

            ListView1.Items.Clear()
            For Each fileInfo In dirInfo.GetFiles("*.txt").OrderByDescending(Function(f) f.LastWriteTime).ToList()

                Dim li As New ListViewItem(New String() {fileInfo.Name, fileInfo.LastWriteTime})

                ListView1.Items.Add(li)
            Next


        Catch ex As Exception

        End Try


    End Sub

    Private Sub BorrarNotaToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles BorrarNotaToolStripMenuItem.Click

        Try

            Dim strFile As String
            strFile = TreeView1.SelectedNode.FullPath & "\" & ListView1.SelectedItems(0).Text

            'Borra
            My.Computer.FileSystem.DeleteFile(strFile)
            doc.Clear()
            txtNoteName.Clear()


            'Refrescar
            UpdateListNotas()

        Catch ex As Exception

        End Try



    End Sub

    Private Sub TabControl1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles TabControl1.SelectedIndexChanged

        Try
            If TabControl1.SelectedTab Is TabPage2 Then

                Dim md As String

                Dim pipeline As MarkdownPipeline = New MarkdownPipelineBuilder().UseAdvancedExtensions().Build()

                md = Markdown.ToHtml(CStr(doc.Text).Replace(vbCrLf, vbLf), pipeline)


                WebBrowser1.DocumentText = (estilo & md).Replace("<img src=" & Chr(34), "<img src=" & Chr(34) & TreeView1.SelectedNode.FullPath & "\")


            End If



        Catch ex As Exception

            'MsgBox(ex.Message)

        End Try


    End Sub

    Private Sub ConfiguracionToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ConfiguracionToolStripMenuItem.Click
        frmDropBox.ShowDialog()

    End Sub


    Private Sub SintaxisMarkDownToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles SintaxisMarkDownToolStripMenuItem.Click
        Dim webAddress As String = "http://joedicastro.com/pages/markdown.html"
        Process.Start(webAddress)
    End Sub
End Class
